package com.wxg;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;

public class GetTableClumn {

    public static void main(String[] args) {

        //oracle.jdbc.driver.OracleDriver
        //com.microsoft.sqlserver.jdbc.SQLServerDriver
        String DbDriver = "com.mysql.jdbc.Driver";
        //DbDriver = "oracle.jdbc.driver.OracleDriver";
        DbDriver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
        //jdbc:mysql://localhost:3306/test
        //jdbc:sqlserver://localhost:1433;DatabaseName=HIS_HD
        //jdbc:oracle:thin:@localhost:1521:orcl
        String url = "jdbc:mysql://localhost:3306/test";
        url = "jdbc:sqlserver://localhost:1433;DatabaseName=HIS_HD";
        String user = "sa";
        String password = "hisadmin";
        //
        Connection conn = null;
        ResultSet rs = null;
        BufferedReader br = null;
        try {
            Class.forName(DbDriver);
            
            //
            conn = DriverManager.getConnection(url, user, password);
            DatabaseMetaData dbmetadata = conn.getMetaData();
            //
            String[] types = {"TABLE"};
            rs = dbmetadata.getTables(null, null, null, types);
            String tablename = null;
            while(rs.next()){
                tablename = rs.getString("TABLE_NAME");
                System.out.println(tablename);
            }
            //接受键盘输入
            br = new BufferedReader(new InputStreamReader(System.in));
            String tbName = br.readLine();
            
            //
            rs = dbmetadata.getColumns(null, null, tbName, null);
            String columnName = null;
            while(rs.next()){
                columnName = rs.getString("COLUMN_NAME");
                System.out.println(columnName);
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally{
            try {
                if(null != rs){
                    rs.close();
                }
                if (null != conn){
                    conn.close();
                }
                if(null != br){
                    br.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
    }
}
